#include "TemplatedResponse.h"
#include "CommonUtil.h"
#include "stdlib.h"

TemplatedResponse::TemplatedResponse()
{
}

TemplatedResponse::~TemplatedResponse(void)
{
}

void TemplatedResponse::init(std::string def)
{
	if (startsWith(def, "MULTIPLE{") && endsWith(def, "}")) {
		std::vector<std::string> candidates;
		splitString(def.substr(9, def.length()-10), "|", candidates);
		trimAll(candidates);
		for (int iCand = 0; iCand < (int)(candidates.size()); iCand++) {
			if (!candidates[iCand].empty())
				m_candidates.push_back(candidates[iCand]);
		}
	}
}

std::string TemplatedResponse::genResponse() 
{
	if (!isValid())	return "";
	return m_candidates[rand()%m_candidates.size()];
}

std::string TemplatedResponse::genResponse(std::map<std::string, std::string>& variables) 
{
	if (!isValid())	return "";
	std::string response = m_candidates[rand()%m_candidates.size()];
	
	std::map<std::string, std::string>::iterator iterVar;
	for (iterVar = variables.begin(); iterVar != variables.end(); iterVar++) {
		response = replaceAll(response, "["+iterVar->first+"]", iterVar->second);
	}
	return response;
}
